// PostList2.js

import React, { Component } from "react";

import PostItem from "./PostItem2";

class PostList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            posts: []
        };
        this.timer = null;
        this.handleVote = this.handleVote.bind(this);   // in ec6 class, must manually bind the actual reference of this
        this.handleSave = this.handleSave.bind(this);   // in ec6 class, must manually bind the actual reference of this
    }

    componentDidMount() {
        // mock getting data from server by setTimeout
        this.timer = setTimeout(() => {
            this.setState({
                posts: [
                    {id:1, title:'let\'s talk about react', author: 'Tina', date: '2022-11-21 21:37', vote: 0},
                    {id:2, title: 'which frontend framework do you like best', author: 'Andy', date: '2022-11-19 10:00', vote: 0},
                    {id:3, title: 'time of web app is coming', author: 'Judy', date: '2022-11-23 6:00', vote: 0}
                ]
            });
        }, 1000);
    }

    componentWillUnmount() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
    }

    handleVote(id) {
        // filter by the post id
        const posts = this.state.posts.map(item => {
            const newItem = item.id === id ? {...item, vote: ++item.vote} : item;
            return newItem;
        })
        this.setState({
            posts
        });
    }
    handleSave(post) {
        const posts = this.state.posts.map(item => {
            const newItem = item.id === post.id ? post : item;
            return newItem;
        })
        this.setState({
            posts
        })
    }

    render() {
        return (
            <div className="container">
                <h2>post list:</h2>
                <ul>
                    {this.state.posts.map(item => 
                        <PostItem
                            key = {item.id}
                            post = {item}
                            onVote = {this.handleVote}
                            onSave = {this.handleSave}
                        />
                    )}
                </ul>
            </div>
        );
    }
}

export default PostList;
